import React, { useState, useMemo } from 'react';
import s from './style.module.css';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import Helper from '../../../components/Helper';
import { withRouter } from 'react-router';
import SecurityRating from '../../JobManage/WebTask/TaskDetail/SecurityRating';
import { IconS } from '../../JobManage/WebTask/TaskDetail/SecurityRating/picture';
import PropTypes from 'prop-types';
import Label from '../../../components/Label';
import Select from '@knownsec/react-component/dist/Select';
import fetchFer from 'API/fetch';
import { turnToUrlparam, GetQueryString } from '../../../helpers/getUrlParams';
import { datetime, timeChange } from '../../../../common/formatter';
import cn from 'classnames';
import HostDetail from './HostDetail';
const infoObj = {
	name: '资产名称',
	target: '资产地址',
	scan_count: '检测次数',
	reactive_status: '响应状态',
};

function Detail({
	match: {
		params: { assetType },
	},
	location,
}) {
	const jid = GetQueryString(location.search, 'jid');
	const tid = GetQueryString(location.search, 'tid');
	const atid = GetQueryString(location.search, 'id');
	const type = GetQueryString(location.search, 'type');
	const last = GetQueryString(location.search, 'last');
	const [selVal, setSelVal] = useState([]);
	const [timeOpt, setTimeOpt] = useState([]);
	const [manualT, setManualT] = useState();
	const [detail, setDetail] = useState([{}]);
	const getHostDetail = async () => {
		const sendData = {
			id: selVal[0],
			job_id: jid,
		};
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(
			`/api/v2/tasks/vul_host/detail/overview?${params}`,
			{
				method: 'GET',
			}
		);
		console.log(res);
		setDetail(res);
	};
	const resDemo = e => {
		const aa = e && e.replace(/\d+/g, `<span style='color: #EA0028'>$&</span>`);
		return aa;
	};
	// 获取时间列表
	useMemo(async () => {
		let url = '';
		if (last) {
			url = `/api/v2/repodatas/task_completed_times?job_id=${jid}&task_types=hostVul`;
		} else {
			url = `/api/v2/repodatas/task_completed_times?job_id=${jid}&asset_task_id=${atid}&task_types=hostVul`;
		}
		const res = await fetchFer(url, {
			method: 'GET',
		}).catch(error => {
			return error;
		});
		const time = res.data.map(e => {
			const differenceTime = Date.now() - new Date(datetime(e.time)).getTime();
			if (e.id === tid) {
				setManualT(datetime(e.time));
				setSelVal([e.id]);
			}
			return {
				label: datetime(e.time) + `（${timeChange(differenceTime)}前）`,
				labelHtml: `<p style="display:flex"><span style="width: 150px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">${datetime(
					e.time
				)}</span>
        <span style="width: 85px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">(${timeChange(
					differenceTime
				)}前)</span></p>`,
				value: e.id,
			};
		});
		setTimeOpt(time);
		!last && setSelVal([time[0].value]);
	}, [assetType]);
	React.useEffect(() => {
		getHostDetail();
	}, [selVal, assetType]);
	return (
		<div className={s.taskMain}>
			<div className="df aic jcsb pr24">
				<Breadcrumb>
					<Item key="job-manage" disabled>
						任务管理
					</Item>
					<Item key="host-task">主机安全监测</Item>
					<Item key="">监测结果</Item>
				</Breadcrumb>
				{type === 'schedule' ? (
					<div className="df aic">
						历史监测结果:
						<Select
							pro
							value={selVal}
							placeholder="检测历史"
							option={timeOpt}
							className={s.sel}
							clearable
							onChange={({ selectedItem }) => {
								setSelVal([selectedItem[0].value]);
							}}
						/>
					</div>
				) : (
					<div>监测完成时间：{manualT || '- -'}</div>
				)}
			</div>
			<div className={cn(s.content, s.pt0)}>
				<div className={s.header}>
					<div className={s.left}>
						<SecurityRating score={100 - (detail?.score || 0)} />
					</div>
					<div className={s.right}>
						{/* <div>
						<Download />
						<a>下载报告</a>
					</div> */}
						<div className={s.title}>任务名称：{detail.task_name}</div>
						<div className={s.info}>
							<div className={cn(s.df, s.aic, s.mb16)}>
								{Object.keys(infoObj)
									.slice(0, 2)
									.map(e => {
										return (
											<p className={cn(s.flex1)} key={e}>
												<span className={s.infoName}>{infoObj[e]}</span>：
												<span className={s.infoVal}>{detail[e]}</span>
											</p>
										);
									})}
							</div>
							<div className={cn(s.df, s.aic, s.mb16)}>
								{Object.keys(infoObj)
									.slice(2, 4)
									.map(e => {
										return (
											<p className={cn(s.flex1)} key={e}>
												<span className={s.scan_count}>{infoObj[e]}</span>：
												<span className={s.infoVal}>{detail[e]}</span>
											</p>
										);
									})}
							</div>
						</div>
						<div className={s.rBox}>
							<p className={s.rBoxp1}>
								<span className={s.icon}>
									<IconS />
								</span>
								监测结果
								<Helper
									overlay="同步资产最新一次主机安全监测结果。"
									placement="top"
								/>
							</p>
							<p
								dangerouslySetInnerHTML={{ __html: resDemo(detail.result) }}
								className={s.infoVal}
							></p>
						</div>
					</div>
				</div>
				<div className={s.infoBody}>
					<Label className={s.labelDetail}>监测详情</Label>
					<HostDetail jid={jid} tid={selVal[0]} atid={atid} />
				</div>
			</div>
		</div>
	);
}
Detail.propTypes = {
	location: PropTypes.any,
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
			jid: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(Detail);
